#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


 // Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==nullptr){
            return nullptr;
        }
        int length = 0;
        ListNode* curr = head;
        while(curr!=nullptr){
            ++length;
            curr = curr->next;
        }
        
        k %= length;
        if(length==1||k==0){
            return head;
        }
        ListNode* low = head;
        ListNode* fast = head;
        int i = 0;
        while(fast->next!=nullptr){
            if(i<k){
                fast = fast->next;
                ++i;
            }
            else{
                low = low->next;
                fast = fast->next;
            }
        }
        ListNode* rehead = low->next;
        low->next = nullptr;
        fast->next = head;
        return rehead;
    }
};

int main(){
    Solution S;
    ListNode* head= new ListNode(1);
    head->next = new ListNode(2);
    // head->next->next = new ListNode(3);
    // head->next->next->next = new ListNode(4);
    // head->next->next->next->next = new ListNode(5);
    ListNode* rehead = S.rotateRight(head,2);
    return 0;
}